/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, message, Modal, Row, Divider, Cascader } from 'antd';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ loading }) => ({
  loading:
    loading.effects['custedit/getAreaList'] || loading.effects['custedit/getMailInfo']
      ? false
      : loading.models.custedit,
  confirmLoading:
    loading.effects['custedit/insertSubmit'] || loading.effects['custedit/updateSubmit'],
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      custId: null,
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
      provCityAreaList: [],
      mailArea: '',
    };
    this.columns = [
      {
        title: '联系人姓名',
        dataIndex: 'contPerName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '联系人电话',
        dataIndex: 'contPerPhone',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '邮寄地址',
        dataIndex: 'mailArea',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '详细地址',
        dataIndex: 'mailAddr',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a onClick={e => this.update(e, record.mailAddrId, record.areaList)}>修改</a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { custId } = this.props;
    const { nowPage, pageNum } = this.state;
    this.setState({ custId });
    this.getAreaList(null, data => {
      data.map(item => {
        const temp = item;
        temp.label = item.areaName;
        temp.value = item.areaId;
        temp.isLeaf = false;
      });
      this.setState({ provCityAreaList: data });
    });
    this.getList(nowPage, pageNum);
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { custId, dispatch } = this.props;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' MAIL_ADDR_ID DESC',
    };
    const params = { custId, pageArg };
    dispatch({
      type: 'custedit/getMailList',
      payload: params,
    }).then(res => {
      if (res.success) {
        const data = res.data.pageRecords;
        data.map(item => {
          const temp = item;
          temp.remark = item.remark ? item.remark : '暂无';
        });
        this.setState({
          dataSource: res.data.pageRecords,
          cmTotal: res.data.totalCount,
        });
      } else {
        this.setState({ cmTotal: 0, dataSource: [] });
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.mailAddrId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要刪除此条邮寄地址信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'custedit/deleteMail',
          payload: {
            generalIds: rowKeys,
          },
        }).then(res => {
          if (res.success) {
            const { cmTotal, nowPage, pageNum } = this.state;
            const selectedLen = selectedRowKeys.length;
            if (nowPage > 1 && (cmTotal % pageNum === selectedLen || pageNum === selectedLen)) {
              this.getList(nowPage - 1, pageNum);
              this.setState({ nowPage: nowPage - 1 });
            } else {
              this.getList(nowPage, pageNum);
            }
            this.setState({ selectedRowKeys: [] });
            message.success('删除成功！');
          } else {
            message.warning(`${res.message || '删除失败！'}`);
          }
        });
      },
    });
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/getAreaList',
      payload: {
        parentId: areaId,
        busiFlag: 2,
      },
    }).then(res => {
      callback(res.data);
    });
  };

  // 地区选择：省市区
  selectProvCityArea = (value, selectedOptions) => {
    let mailArea = '';
    selectedOptions.map((item, index) => {
      mailArea += (index > 0 ? '/' : '') + item.label;
    });
    mailArea = mailArea.trim();
    this.setState({ mailArea });
  };

  loadAreaData = selectedOptions => {
    const { provCityAreaList } = this.state;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].value;
    targetOption.loading = true;
    const childrenData = [];
    this.getAreaList(parentId, data => {
      data.map(item => {
        const temp = item;
        temp.isLeaf = item.areaNature === 6;
        temp.label = item.areaName;
        temp.value = item.areaId;
        childrenData.push(item);
      });
    });
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        provCityAreaList: [...provCityAreaList],
      });
    }, 1000);
  };

  // 新增数据
  add = () => {
    const { form } = this.props;
    this.handleModalVisible(true, true);
    form.resetFields();
  };

  update = (e, mailAddrId, areaList) => {
    e.preventDefault();
    const { custId } = this.props;
    const rowKeys = [];
    const areaIdList = [];
    rowKeys.push(mailAddrId);
    let mailArea = '';
    const { provCityAreaList } = this.state;
    const cityData = [];
    const countyData = [];
    areaList.forEach((item, index) => {
      areaIdList.push(item.areaId);
      mailArea += (index > 0 ? '/' : '') + item.areaName;
    });
    mailArea = mailArea.trim();
    this.setState({ selectedRowKeys: rowKeys, custId, mailArea });
    switch (areaIdList.length) {
      case 1:
        this.getSetInfo(mailAddrId, areaIdList);
        break;
      case 2:
        this.getAreaList(areaIdList[0], data => {
          const cityDatas = [];
          data.map(area => {
            cityDatas.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            const obj = p;
            if (p.areaId === areaIdList[0]) {
              obj.children = cityDatas;
            }
          });
          this.setState({ provCityAreaList }, () => {
            this.getSetInfo(mailAddrId, areaIdList);
          });
        });
        break;
      case 3:
        // 获取市
        this.getAreaList(areaIdList[0], data => {
          data.map(area => {
            cityData.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            const temps = p;
            if (p.areaId === areaIdList[0]) {
              temps.children = cityData;
            }
          });
          // 获取区县
          this.getAreaList(areaIdList[1], datas => {
            datas.map(area => {
              countyData.push({
                label: area.areaName,
                value: area.areaId,
                isLeaf: area.areaNature === 6,
              });
            });
            provCityAreaList.map(p => {
              if (p.areaId === areaIdList[0]) {
                // 判断省
                p.children.map(c => {
                  const temp = c;
                  if (c.value === areaIdList[1]) {
                    // 判读市
                    temp.children = countyData;
                  }
                });
              }
            });
            this.setState({ provCityAreaList }, () => {
              this.getSetInfo(mailAddrId, areaIdList);
            });
          });
        });
        break;
      default:
        break;
    }
  };

  // 获取修改信息并赋值
  getSetInfo = (mailAddrId, areaIdList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/getMailInfo',
      payload: {
        mailAddrId,
      },
    }).then(res => {
      if (res.success && res.data) {
        const { form } = this.props;
        this.handleModalVisible(true, false);
        const getFieldsList = form.getFieldsValue();
        this.setState({
          mailCounty: res.data.mailCounty,
        });
        Object.keys(getFieldsList).forEach(key => {
          if (res.data[key]) {
            if (key === 'mailArea') {
              res.data[key] = areaIdList;
            }
            form.setFieldsValue({ [key]: res.data[key] });
          }
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ selectedRowKeys: [] });
  };

  // 新增修改提交数据
  submitData = () => {
    const { isAdd, custId, selectedRowKeys, nowPage, pageNum, mailArea, mailCounty } = this.state;
    const { form, dispatch } = this.props;
    let submitData = {};
    const submitUrl = isAdd ? 'custedit/insertSubmit' : 'custedit/updateSubmit';
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = values;
        temp.mailCounty = values.mailArea[values.mailArea.length - 1] || mailCounty;
        delete temp.vatCoprNameS;
        delete temp.taxerIdNoS;
        delete temp.mailArea;
        delete temp.invoiceLicense;
        Object.keys(values).forEach(key => {
          const obj = values;
          if (values[key] && values[key].key) {
            obj[key] = values[key].key;
          } else {
            obj[key] = values[key] ? values[key] : '';
          }
        });
        submitData = isAdd
          ? { custId, mailArea, ...values }
          : { custId, mailArea, ...values, mailAddrId: selectedRowKeys[0] };
        dispatch({
          type: submitUrl,
          payload: submitData,
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
            this.getList(nowPage, pageNum);
            this.setState({ selectedRowKeys: [], modalVisible: false });
          } else {
            message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
          }
        });
      }
    });
  };

  render() {
    const {
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      provCityAreaList,
      nowPage,
      pageNum,
      cmTotal,
    } = this.state;
    const {
      form: { getFieldDecorator },
      confirmLoading,
    } = this.props;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: rows => {
        this.setState({ selectedRowKeys: rows });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      width: 600,
      title: isAdd ? '新增邮寄地址信息' : '修改邮寄地址信息',
      visible: modalVisible,
      confirmLoading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
      destroyOnClose: true,
    };
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.mailAddrId}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="联系人姓名">
              {getFieldDecorator('contPerName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={30} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="联系人电话">
              {getFieldDecorator('contPerPhone', {
                rules: [
                  {
                    required: true,
                    message: '固话或手机',
                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={12} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="邮寄地址">
              {getFieldDecorator('mailArea', {
                rules: [{ type: 'array', required: true, message: '请选择(市区或县级)', min: 2 }],
              })(
                <Cascader
                  placeholder="请选择"
                  options={provCityAreaList}
                  loadData={this.loadAreaData}
                  onChange={this.selectProvCityArea}
                  changeOnSelect
                />
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="详细地址">
              {getFieldDecorator('mailAddr', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请选择' }],
              })(<Input placeholder="请输入" maxLength={200} />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default BasicList;
